﻿using System.Linq;
using System.Text;
using MRGSP.SurveyMaster.Core;
using MRGSP.SurveyMaster.Core.Model;
using MRGSP.SurveyMaster.Core.Service.Utils;

namespace MRGSP.SurveyMaster.Service.Utils
{
    public class GridBuilder : IQuestionBuilder
    {
        public string Build(Question q)
        {
            var b = new StringBuilder();
            b.Append(string.Format(@"<div id='qwrap{0}'>", q.Id));
            b.Append(HtmlGeneratorFactory.Generate(q));
            b.Append("<table><thead><tr><th>&nbsp;</th>");

            if (q.HasChildren())
            {
                var firstChild = q.Children.First();

                foreach (var gridColumn in firstChild.Children)
                {
                    b.Append(string.Format(
                    @"<th><div id='gridcolwrap{1}'>{0}</div></th>",
                        HtmlGeneratorFactory.Generate(gridColumn), gridColumn.Id));
                }
            }

            b.Append("</tr></thead>");
            var ch = q.Children.Aggregate(string.Empty, (current, row) => 
                current + string.Format("<tr>{0}</tr>", QuestionBuilder.Get(ControlType.GridRow).Build(row)));

            b.Append(ch);
            b.Append("</table></div>");
            return b.ToString();
        }
    }
}